const app = getApp();
const userApi = require('../../api/user.js'); 

Page({
  data: {
    userInfo: {
      nickname: '用户12345',
      avatar: 'https://cdn-icons-png.flaticon.com/512/149/149071.png',
      status: '0',
      credit: 60,
    },
    averageScore: 0
  },

  onLoad() {
    if (!app.globalData.hasLogin) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        wx.redirectTo({ url: '/pages/login/login' });
      }, 1500);
      return;
    }
    this.loadData();
  },
  onShow() {
    if (app.globalData.hasLogin) {
      this.loadData();
    }
  },
    async loadData() {
        const res = await userApi.getUser();
        console.log('个人中心:',res);
        let userInfo = res.data;
        const minioPrefix = 'http://localhost:9000/';
        if (!userInfo.avatar || userInfo.avatar === 'undefined' || userInfo.avatar === '') {
            userInfo.avatar = 'https://cdn-icons-png.flaticon.com/512/149/149071.png';
        } else {
            userInfo.avatar = minioPrefix + userInfo.avatar.replace(/^\/+/, '');
        }

        this.setData({ userInfo });
        wx.setStorageSync('userInfo', JSON.stringify(userInfo));
        const userId = userInfo.id;
        if (userId) {
            this.loadUserAverageScore(userId);
        }},
        async loadUserAverageScore(userId) {
            console.log('查询评分，用户ID：', userId);
            const token = wx.getStorageSync('token');
            if (!token) return;

            try {
                const res = await new Promise((resolve, reject) => {
                    wx.request({
                        url: 'http://localhost:8080/scorings/query',
                        method: 'GET',
                        header: { token },
                        data: { userId },
                        success: (res) => resolve(res.data),
                        fail: (err) => reject(err)
                    });
                });

                console.log('评分接口返回：', res);
                if (res.code === 200 && res.data) {
                    const { scoring, number } = res.data;
                    // 计算平均分
                    const average = number > 0 ? scoring / number : 0;
                    this.setData({ averageScore: average }, () => {
                        console.log('平均分已更新：', this.data.averageScore);
                    });
                } else {
                    this.setData({ averageScore: 0 });
                }
            } catch (err) {
                console.error('查询平均分失败：', err);
                this.setData({ averageScore: 0 });
            }
    },

  chooseAvatar() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'], 
      success(res) {
        const tempFilePath = res.tempFilePaths[0]; 
        that.uploadAvatar(tempFilePath);
      }
    });
  },
async uploadAvatar(filePath) {
    wx.showLoading({ title: '上传中...' });
    const res = await userApi.updateAvatar(filePath);
    console.log('成功修改头像:',res);
    if (res.code === 200) {
      wx.showToast({ title: '头像更换成功' });
      this.setData({ 'userInfo.avatar': res.data.avatar });
      this.loadData();
    } else {
      wx.showToast({ title: '头像更换失败', icon: 'none' });
    }
},
  handleBack() {
    wx.switchTab({
      url: '/pages/home/index' 
    });
  },

  navigateToProfile() {
    wx.navigateTo({ url: '/pages/profile/profile' });
  },

  navigateToCertification() {
    wx.navigateTo({ url: '/pages/real-name-auth/real-name-auth' });
  },

  navigateToOrders() {
    wx.navigateTo({ url: '/pages/order/order' });
  },

  navigateToSignIn() {
    wx.navigateTo({ url: '/pages/signIn/signIn' });
  },
  navigateToWallet() {
    wx.navigateTo({ url: '/pages/wallet/wallet' });
  },
  navigateToCustomerService() {
    wx.navigateTo({ url: '/pages/chatAi/chatai'});
  },

  handleLogout() {
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      confirmText: '确定',
      cancelText: '取消',
      success: async function(res) {
        if (res.confirm) {
          try {
            const res = await userApi.exit();
            if (res.code === 200) {
              wx.showToast({ title: '退出登录成功' });
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
              app.globalData.hasLogin = false;
              app.globalData.token = '';
              setTimeout(() => {
                wx.redirectTo({ url: '/pages/login/login' });
              }, 1500);
            }
          } catch (err) {
            console.error('退出登录失败：', err);
            wx.showToast({ title: '退出失败，请重试', icon: 'none' });
          }
        } else {
          wx.showToast({ title: '已取消退出', icon: 'none' });
        }
      }
    });
  }
});